package com.one.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.one.bean.*;
import com.one.constant.DBStatusConstant;
import com.one.constant.RedisPrefixConstant;
import com.one.constant.RequestReturnConstant;
import com.one.constant.SystemConstant;
import com.one.mapper.*;
import com.one.service.ProductService;
import com.one.util.DatabasePropertiesUtil;
import com.one.util.RequestReturn;
import com.one.util.RequestReturnFactory;
import com.one.utils.JedisUtil;
import com.one.vo.ProductVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName: ProductServiceImpl
 * @Date: 2022/1/14 11:54
 * @Description: 商品业务层实现类
 */
@Service
public class ProductServiceImpl implements ProductService {

    /**
     * 商品持久层对象
     */
    @Autowired(required = false)
    private ProductMapper productMapper;

    /**
     * 商品分类持久层对象
     */
    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    /**
     * 商品颜色配置持久化对象
     */
    @Autowired(required = false)
    private ColorMapper colorMapper;

    /**
     * 商品尺寸配置持久化对象
     */
    @Autowired(required = false)
    private SizeMapper sizeMapper;

    /**
     * 商品视图持久层对象
     */
    @Autowired(required = false)
    private ProductViewMapper productViewMapper;

    /**
     * 用户收藏和足迹持久层对象
     */
    @Autowired(required = false)
    private CollectFootpointMapper collectFootpointMapper;
    /**
     * 评论持久层对象
     */
    @Autowired(required = false)
    private CommentMapper commentMapper;

    /**
     * jedis对象
     */
    @Autowired(required = false)
    private JedisUtil jedisUtil;

    @Override
    public ProductVo queryProductDetailById(Integer userId, Integer id, String sessionId) {
        // 判断当前用户有没有登录，
        if (!Objects.isNull(userId)) {
//            // 存在本地记录的话，就添加进记录中，否则就不添加
//            if (jedisUtil.exists(RedisPrefixConstant.MOGU_FOOTPOINT_PREFIX + sessionId)) {
//                List<String> footPoints = jedisUtil.lrange(RedisPrefixConstant.MOGU_FOOTPOINT_PREFIX + sessionId, 0, -1);
//                footPoints.forEach(footPoint->{
//                    System.out.println("footPoint = " + footPoint);
//                });
//            }
            // 更新历史记录到数据库
            footPointToMysql(userId, id);
        }
//        } else {
//            // 未登录时，将浏览记录记录到redis中 ，只记录商品id和sessionId
//            footPointToRedis(id, sessionId);
//        }

        // 创建一个product的条件查询器
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        // 根据id 查出一条商品数据
        Product product = productMapper.selectById(id);
        // 对查询出来的数据进行转换并返回
        return this.productToProductVo(product);
    }


    @Override
    public String queryProductNameById(Integer id) {
        if (Objects.isNull(productMapper.selectById(id))) {
            return null;
        }
        return productMapper.selectById(id).getProductName();
    }


    @Override
    public RequestReturn<Map<String, Object>> queryProductStock(Integer productId) {
        Map<String, Object> resultMap = new HashMap<>();
        Product product = productMapper.selectById(productId);
        if (Objects.isNull(product)) {
//            resultMap.put("code", RequestReturnConstant.NO_PRODUCT_CODE);
//            resultMap.put("message","没有该商品!");
            return RequestReturnFactory.fail(RequestReturnConstant.NO_PRODUCT_CODE, "没有该商品！");
        }
        resultMap.put("productName", product.getProductName());
        resultMap.put("id", product.getId());
        resultMap.put("stockNum", product.getCount());
        if (product.getCount() < 10) {
            resultMap.put("message", "当前商品缺货状态中，如有需要，可以订阅到货提醒！");
        }
        return RequestReturnFactory.success(resultMap);
    }

    @Override
    public RequestReturn<Map<String, Object>> addProductStock(Integer productId, Integer addNum) {
        Map<String, Object> resultMap = new HashMap<>();
        Product product = productMapper.selectById(productId);
        if (Objects.isNull(product)) {
            return RequestReturnFactory.fail(RequestReturnConstant.NO_PRODUCT_CODE, "没有该商品！");
        }
        product.setCount(product.getCount() + addNum);
        int i = productMapper.updateById(product);
        if (i > 0) {
            product = productMapper.selectById(productId);
            resultMap.put("productName", product.getProductName());
            resultMap.put("id", product.getId());
            resultMap.put("stockNum", product.getCount());
        }
        return RequestReturnFactory.success(resultMap);
    }


    /**
     * @Author: yph
     * @Date: 2022/1/14 15:21
     * @return:
     * @Description: 根据ids查询商品分类 传入一个id的list ，获取想对应的数据
     */
    List<Category> queryCategoryListByIds(List<Integer> ids) {
        return categoryMapper.selectList(new QueryWrapper<Category>().in("id", ids));
    }


    /**
     * @Author: yph
     * @Date: 2022/1/14 14:21
     * @return:
     * @Description: 将 Product 对象转换为 ProductVo 对象
     */
    private ProductVo productToProductVo(Product product) {
        // 创建一个ProductVo对象 用于返回
        ProductVo productVo = new ProductVo();
        // 拷贝相同的属性值
        BeanUtils.copyProperties(product, productVo);
        // 对于不需要转换的数据进行转换
        // 1、对副图进行解析并设置到productVo对象中
        productVo.setSubImages(DatabasePropertiesUtil.stringToList(product.getSubImage()));
        // 2、对商品一级、二级分类进行解析并赋值
        productVo.setCategoryFirstName(categoryMapper.selectById(product.getCategoryFirst()).getCategoryName())
                .setCategorySecondName(categoryMapper.selectById(product.getCategorySecond()).getCategoryName())
                // 3、对商品参数进行解析并赋值
                .setParameters(DatabasePropertiesUtil.stringToList(product.getParameter()));
        // 4、获取商品颜色配置
        List<Color> colors = colorMapper.selectList(new QueryWrapper<Color>().in("id", DatabasePropertiesUtil.stringToList(product.getTagColor())));
        productVo.setTagColors(colors.stream().map(Color::getColor).collect(Collectors.toList()));
        // 5、获取商品尺寸配置
        List<Size> sizes = sizeMapper.selectList(new QueryWrapper<Size>().in("id", DatabasePropertiesUtil.stringToList(product.getTagSize())));
        productVo.setTagSizes(sizes.stream().map(Size::getSize).collect(Collectors.toList()))
                // 6、设置商品的类型 单品/全品
                .setType(DBStatusConstant.SINGLE_CODE == product.getType() ? DBStatusConstant.SINGLE_MSG : DBStatusConstant.ENTIRE_MSG)
                // 7、设置商品的上下架状态
                .setStatus(DBStatusConstant.SELLING_CODE == product.getStatus() ? DBStatusConstant.SELLING_MSG : DBStatusConstant.SOLD_OUT_MSG)
                // 8、获取商品销量
                .setSellNum(productViewMapper.selectOne(
                        new QueryWrapper<ProductView>()
                                .select("sales_volume")
                                .eq("id", product.getId())
                ).getSalesVolume())
                // 9、获取商品评价数量
                .setCommentNum(commentMapper.selectCommentCountByProductId(product.getId(), false));
        return productVo;
    }

    /**
     * @Author: yph
     * @Date: 2022/1/21 15:48
     * @return:
     * @Description: 更新历史记录到数据库
     */
    private void footPointToMysql(Integer userId, Integer id) {
        // 根据商品id和用户id查询出是否有过历史记录
        CollectFootpoint collectFootpoint = collectFootpointMapper.selectOne(new QueryWrapper<CollectFootpoint>()
                .eq("user_id", userId)
                .eq("product_id", id)
                .eq("type", DBStatusConstant.USER_FOOTPOINT));
        // 如果之前没有浏览记录 ，直接插入数据
        if (Objects.isNull(collectFootpoint)) {
            collectFootpointMapper.insert(
                    new CollectFootpoint().setType(DBStatusConstant.USER_FOOTPOINT)
                            .setProductId(id)
                            .setUserId(userId)
                            .setCreateDate(new Date())
                            .setUpdateDate(new Date()));
        } else {
            // 如果存在浏览记录，就对其进行修改,只修改时间 和 状态
            collectFootpointMapper.updateById(collectFootpoint.setUpdateDate(new Date()).setStatus(0));
        }
    }

    /**
     * @Author: yph
     * @Date: 2022/1/21 16:06
     * @return:
     * @Description: 如果没有登录，将浏览记录插入到redis中
     */
    private void footPointToRedis(Integer id, String sessionId) {
        // 判断当前是否存在记录
        if (jedisUtil.exists(RedisPrefixConstant.MOGU_FOOTPOINT_PREFIX + sessionId)) {
            // 去除相同的信息
            jedisUtil.lrem(RedisPrefixConstant.MOGU_FOOTPOINT_PREFIX + sessionId, 1, Objects.isNull(id) ? "" : id.toString());
        }
        // 添加到redis中
        jedisUtil.lpush(RedisPrefixConstant.MOGU_FOOTPOINT_PREFIX + sessionId, Objects.isNull(id) ? "" : id.toString());

    }


}
